<template>
  <view class="page_root" data-page-name="工单操作按钮组件" data-page-identification="k_e9gklgicv5">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_g14q7hr2w1 自定义模板_5rykoyhfo6 -->
    <view @tap.stop @catchtap="">
      <u-popup v-model="showMoreMenu" mode="bottom" width="100%" height="30%" class="bgc">
        <view class="popup-container">
          <!-- 固定顶部标题 -->
          <view class="pop-title fixed-header">更多操作</view>

          <view class="popup-more-btn">
            <van-button
              type="primary"
              class="btn-item"
              @click.stop="showResolved(state.gdDetail, 'resolved')"
              :disabled="isResolvedDisabled(state.gdDetail)"
            >
              已解决
            </van-button>
            <van-button
              type="primary"
              class="btn-item"
              :disabled="isCloseDisabled(state.gdDetail)"
              @click.stop="handlerClose(state.gdDetail)"
            >
              关闭
            </van-button>

            <van-button
              type="primary"
              @click.stop="handleEdit(state.gdDetail)"
              :disabled="isEditDisabled(state.gdDetail)"
            >
              编辑
            </van-button>
            <van-button
              type="primary"
              @click.stop="toDelete(state.gdDetail)"
              :disabled="
                !(
                  (state.gdDetail.status === '未开始' || state.gdDetail.status === '待分发') &&
                  state.gdDetail.myCreated
                )
              "
            >
              删除
            </van-button>
          </view>
          <!-- 固定底部按钮 -->
        </view>
      </u-popup>
      <!-- 重新打开确认弹窗 -->
      <u-modal
        :show-cancel-button="true"
        v-model="showReopenConfirm"
        @cancel="showReopenConfirm"
        :content-style="{ padding: '32rpx' }"
        title="重新打开"
        @confirm="handlerReOpen(state.gdDetail)"
      >
        <view class="tip-font">请确认是否重新打开工单？</view>
      </u-modal>
      <!--          关闭工单-->
      <u-modal
        v-model="newSopState.sopCloseVisible"
        @cancel="cancelClose"
        @confirm="confirmSopClose"
        :show-cancel-button="true"
        width="90%"
        title="关闭"
        :mask-closable="false"
        async-close="true"
        ref="closeModalRef"
      >
        <!--              如果是sop展示-->
        <view class="no-need-tip">
          <ExclamationCircleOutlined style="color: #fab221" />
          <u-alert-tips
            type="warning"
            title="请确认是否关闭该工单？"
            description="请填写备注注明原因"
          ></u-alert-tips>
        </view>
        <u-form :model="newSopState" :rules="rules" label-position="top" ref="closeRef">
          <u-form-item label="备注" required prop="closeRemark">
            <u-input
              placeholder="请输入"
              type="textarea"
              v-model="newSopState.closeRemark"
              border
            ></u-input>
          </u-form-item>
        </u-form>
      </u-modal>
      <!--          关闭工单-->
      <!--          删除-->
      <u-modal
        centered
        v-model="state.deleteVisible"
        title="删除"
        width="90%"
        @confirm="handleDelete"
        :show-cancel-button="true"
        async-close="true"
        @cancel="
          () => {
            state.deleteVisible = false;
            resetCurrentData();
          }
        "
        ref="deleteModalRef"
      >
        <!--                请确认是否删除该工单任务，如该工单建立了子工单请先对子工单进行解决后在进行删除操作。-->
        <u-form :model="sonState" :rules="rules" label-position="top" ref="deleteRef">
          <u-form-item label="备注" required prop="deleteRemark">
            <u-input
              placeholder="请输入"
              type="textarea"
              v-model="sonState.deleteRemark"
              border
            ></u-input>
          </u-form-item>
        </u-form>
      </u-modal>
      <!--          删除-->
      <!--          流转变更-->
      <van-popup
        v-model:show="show.solverList"
        position="bottom"
        :style="{
          padding: '0 32rpx',
          height:'50%',
          zIndex:'10079'
        }"
      >
        <van-picker
          :columns-field-names="{ text: 'label', value: 'value' }"
          :columns="state.allUser"
          @confirm="onConfirm('solverList', $event)"
          @cancel="show.solverList = false"
        />
      </van-popup>
      <u-modal
        centered
        v-model="newState.circulationVisible"
        title="流转"
        width="90%"
        :async-close="true"
        @confirm="confirmCirculation"
        @cancel="cancelCirculation"
        :show-cancel-button="true"
        ref="circulatuonModalRef"
      >
        <u-form
          ref="circulationFormRef"
          :model="newState.circulationForm"
          :rules="rules"
          label-position="top"
        >
          <u-form-item label="" prop="solverList">
            <u-input
              type="select"
              @click="showPicker('solverList')"
              placeholder="解决人"
              v-model="newState.circulationForm.solverList"
              border
            ></u-input>
          </u-form-item>
        </u-form>
      </u-modal>
      <!--          流转变更-->
      <!-- 流转变更 -->
      <!--            改变根因分析提示-->
      <van-dialog
        v-model:show="tipState.visible"
        title="提示"
        show-cancel-button
        confirm-button-text="确定"
        cancel-button-text="取消"
        @confirm="confirmRoot"
        teleport="body"
        @cancel="cancelRoot"
        :z-index="999999"
      >
        <div class="text-center text-gray-600"> 修改将清空当前根因分析内容，是否继续？ </div>
      </van-dialog>
      <!--            改变根因分析提示-->
      <!-- 开始解决确认弹窗 -->
      <u-modal
        v-model="showOpen"
        width="90%"
        @confirm="confirmResolving(state.gdDetail)"
        @cancel="cancelResolving"
        title="开始解决"
        :show-cancel-button="true"
        :async-close="true"
        border-radius="32"
        ref="resolvingRef"
      >
        <view class="tip-font">确定开始处理工单吗？</view>
      </u-modal>
      <!-- 开始解决确认弹窗 -->
      <!-- 已解决确认弹窗 -->
      <u-popup
        class="bgc"
        v-model="showResolvedVisible"
        mode="bottom"
        height="60%"
        :mask-close-able="false"
        border-radius="32"
        closeable
        @open="initQuillEditors"
        @close="destroyQuillEditors"
        :custom-style="{ overflow: 'hidden' }"
      >
        <!-- 使用 Flex 布局容器 -->
        <view class="popup-container">
          <!-- 固定顶部标题 -->
          <view class="pop-title fixed-header">{{
            resolvedType === 'noNeed' ? '无需解决' : '已解决'
          }}</view>

          <!-- 可滚动的内容区域 -->
          <scroll-view class="pop-content scrollable-content" scroll-y :show-scrollbar="false">
            <view class="no-need-tip" v-if="resolvedType === 'noNeed'">
              <u-alert-tips
                v-if="resolvedType === 'noNeed'"
                type="warning"
                title="请确认是否无需解决该工单？"
                description="请填写根因分析和备注，注明原因。"
              ></u-alert-tips>
            </view>
            <u-form ref="rootRef" :model="rootState" :rules="rules" label-position="top">
              <!-- 责任方 -->
              <u-form-item label="责任方" prop="responsibleParty" required>
                <u-input
                  type="select"
                  placeholder="请选择"
                  v-model="rootState.responsibleParty"
                  @click="showPicker('responsibleParty')"
                  border
                ></u-input>
                <van-popup v-model:show="show.responsibleParty" position="bottom">
                  <van-picker
                    :columns-field-names="{ text: 'itemName', value: 'itemName' }"
                    :columns="rootState.responsiblePartyList"
                    @confirm="onConfirm('responsibleParty', $event)"
                    @cancel="show.responsibleParty = false"
                  />
                </van-popup>
              </u-form-item>
              <!-- 业务类型 -->
              <u-form-item label="业务类型" prop="businessType" required>
                <u-input
                  type="select"
                  placeholder="请选择"
                  v-model="rootState.businessType"
                  @click="showPicker('businessType')"
                  border
                ></u-input>
                <van-popup v-model:show="show.businessType" position="bottom">
                  <van-picker
                    :columns-field-names="{ text: 'itemName', value: 'itemName' }"
                    :columns="rootState.businessTypeList"
                    @confirm="onConfirm('businessType', $event)"
                    @cancel="show.businessType = false"
                  />
                </van-popup>
              </u-form-item>
              <!-- 根因分析 -->
              <u-form-item label="根因分析" prop="rootCauseClassify" required>
                <u-input
                  type="select"
                  placeholder="请选择"
                  v-model="rootState.rootCauseClassify"
                  @click="showPicker('rootCauseClassify')"
                  border
                ></u-input>
                <van-popup v-model:show="show.rootCauseClassify" position="bottom">
                  <van-picker
                    :columns-field-names="{ text: 'itemName', value: 'itemName' }"
                    :columns="rootState.rootCauseClassifyList"
                    @confirm="onConfirm('rootCauseClassify', $event)"
                    @cancel="show.rootCauseClassify = false"
                  />
                </van-popup>
              </u-form-item>
            </u-form>
            <!-- 富文本描述 -->
            <view class="editor-wrap">
              <view class="label">根因详情</view>
              <div id="rootQuillEditor" class="quill-editor" ref="rootQuillEditor"></div>
            </view>
            <view class="editor-wrap" v-if="resolvedType === 'resolved'">
              <view class="label">解决方案详述</view>
              <div id="resolvedQuillRef" class="quill-editor" ref="resolvedQuillRef"></div>
            </view>
            <!-- 无需解决的备注 -->
            <u-form
              ref="noNeedRef"
              :model="sonState"
              :rules="rules"
              v-if="resolvedType === 'noNeed'"
              label-position="top"
            >
              <u-form-item label="备注" prop="noNeedRemark" required>
                <u-input type="textarea" v-model="sonState.noNeedRemark" border></u-input>
              </u-form-item>
            </u-form>
            <view class="pop-footer fixed-footer">
              <u-button
                type="primary"
                :custom-style="customStyle"
                class="can-btn"
                @click="cancelResolved"
                >取消</u-button
              >
              <u-button
                type="primary"
                class="ok-btn"
                @click="saveRoot"
                :custom-style="customStyleSubmit"
                :loading="newState.changeStatusLoading"
                >确定</u-button
              >
            </view>
          </scroll-view>

          <!-- 固定底部按钮 -->
        </view>
      </u-popup>
      <!-- 已解决确认弹窗 -->

      <view class="father-last" @click.stop>
        <view class="show-more" @click.stop="showMoreMenu = true"> 更多 </view>
        <view class="other-btn">
          <van-config-provider :theme-vars="grayBtnthemeVars">
            <van-button
              class="btn-item"
              @click.stop="showCirculation(state.gdDetail)"
              :disabled="isCirculationDisabled(state.gdDetail)"
            >
              流转
            </van-button>
          </van-config-provider>
          <van-config-provider :theme-vars="grayBtnthemeVars">
            <van-button
              @click.stop="showResolved(state.gdDetail, 'noNeed')"
              :disabled="isNoNeedSolveDisabled(state.gdDetail)"
            >
              无需解决
            </van-button>
          </van-config-provider>
          <!-- 状态判断按钮 -->
          <template v-if="['已解决', '无需解决', '已关闭'].includes(state.gdDetail.status)">
            <van-button
              type="primary"
              plain
              class="btn-item"
              :disabled="!state.gdDetail.myCreated"
              @click.stop="
                () => {
                  showMoreMenu = false;
                  showReopenConfirm = true;
                }
              "
            >
              重新打开
            </van-button>
          </template>

          <template v-else>
            <van-config-provider :theme-vars="grayBtnthemeVars">
              <van-button
                type="primary"
                class="btn-item"
                @click.stop="showResolving(state.gdDetail)"
                :disabled="isResolvingDisabled(state.gdDetail)"
              >
                开始解决
              </van-button>
            </van-config-provider>
          </template>
        </view>
      </view>
    </view>
    <!-- end vid_g14q7hr2w1 自定义模板_5rykoyhfo6 -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/
  import { handleRedirect } from '@/utils/common';
  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000001237';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
    operationForm: {
      type: [Object],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {
    opeartonForm: getComponentParamsValue(undefined),
  };

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_g14q7hr2w1_props = reactive({
    code: '',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_5rykoyhfo6 ref 的引用
  const vid_g14q7hr2w1_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_g14q7hr2w1_ref };

  const showState = reactive({
    vid_g14q7hr2w1_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_y3vwbxujr6 = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });
  const showShare = ref(false);
  const options = [
    { name: '微信', icon: 'wechat' },
    { name: '微博', icon: 'weibo' },
    { name: '复制链接', icon: 'link' },
    { name: '分享海报', icon: 'poster' },
    { name: '二维码', icon: 'qrcode' },
  ];
  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  import { nextTick } from 'vue';
  import AddOrEditWorkOrder from '../Page3000001236/Page3000001236.vue';
  // 按需导入 Vant 3 组件
  import { Button, Dialog } from 'vant';
  import 'vant/lib/index.css';
  import Quill from 'quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import 'quill/dist/quill.snow.css';
  import { showToast, showFailToast, showSuccessToast } from 'vant';
  // 页面内注册 Vant 组件
  const { appContext } = getCurrentInstance();
  [['van-dialog', Dialog]].forEach(([name, comp]) => appContext.app.component(name, comp));
  onMounted(() => {
    setPageStyle();
  });
  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    const pageRoot = document.querySelector('.page_root');

    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  const grayBtnthemeVars = reactive({
    'button-default-background': 'rgba(0,0,0,0.03)',
    'button-primary-background': 'rgba(51,102,255,0.10)',
    'button-primary-border-color': 'none',
    'button-primary-color': '#3366FF',
    'button-default-border-color': 'none',
    'button-default-color': 'rgba(0,0,0,0.65)',
  });
  const customStyle = reactive({
    backgroundColor: '#fff',
    color: '#262626',
    borderRadius: '16rpx',
    fontWeight: 'r=400',
    borderColor: '#fff',
  });
  const customStyleSubmit = reactive({
    borderRadius: '16rpx',
    backgroundImage: 'linear-gradient(-67deg, #82B0FF 0%, #3366FF 74%)',
    borderColor: '#fff',
    color: '#fff',
  });
  // 子组件
  const show = reactive({
    responsibleParty: false,
    businessType: false,
    rootCauseClassify: false,
    solverList: false,
  });
  const state = reactive({
    gdDetail: {},
    addOrEditVisible: false,
    deleteVisible: false,
  });
  //    新需求
  const newState = reactive({
    changeStatusLoading: false,
    isExpandAll: false,
    circulationVisible: false,
    resolvingVisible: false,
    resolvedVisible: false,
    circulationForm: {
      solverList: [],
      status: '流转',
    },
    resolvingForm: {
      solution: '',
      status: '解决中',
    },
    resolvedForm: {
      solution: '',
      attachmentList: [],
      status: '已解决',
      solutionDetail: '',
    },
    closeForm: {
      status: '关闭',
    },
    workOrderId: undefined,
  });
  const newSopState = reactive({
    sopOkLoading: false,
    sopVisible: false,
    selectedRowKeys: [],
    sopTableData: [],
    //   sop父工单开始解决部分
    sopStartTableList: [],
    //   sop工单无需解决
    solvedSOPList: [],
    //   sop工单关闭
    sopCloseTableData: [],
    sopCloseVisible: false,
    //   sop已拒绝部分
    sopRemainingData: [],
    //   新建SOP子工单里的附件
    sopFileList: [],
    closeLoading: false,
    closeRemark: undefined,
  });
  //   更多弹出
  const showMoreMenu = ref(false);
  //   开始解决
  const showOpen = ref(false);
  //   已解决
  const showResolvedVisible = ref(false);
  //   重新打开
  const showReopenConfirm = ref(false);

  watch(
    () => props.operationForm,
    (val) => {
      state.gdDetail = props.operationForm;
    },
    { immediate: true },
  );
  // 富文本实例
  // ====== 编辑器相关 ======
  const rootQuillEditor = ref(null); // 根因分析 DOM 容器
  const resolvedQuillRef = ref(null); // 解决方案 DOM 容器

  const rootQuill = ref(null); // 根因分析 Quill 实例
  const resolvedQuill = ref(null); // 解决方案 Quill 实例
  const isQuillReady = ref(false);

  const rootContent = ref('');
  const resolvedContent = ref('');
  // 弹窗显示变化时处理

  onUnmounted(() => {
    destroyQuillEditors();
  });

  async function initQuillEditors() {
    // 已经初始化过就不重复创建
    if (isQuillReady.value) return;

    await nextTick();

    // rootQuill
    if (rootQuillEditor.value) {
      // 防止重复挂载同一个节点
      if (rootQuill.value) {
        try {
          rootQuill.value.off('text-change');
        } catch {}
        rootQuill.value = null;
      }

      rootQuill.value = new Quill(rootQuillEditor.value, {
        theme: 'snow',
        modules: {
          toolbar: [['bold', 'italic', 'underline'], [{ color: [] }], ['clean'], ['image']],
        },
      });
    }

    // resolvedQuill
    if (resolvedQuillRef.value) {
      if (resolvedQuill.value) {
        try {
          resolvedQuill.value.off('text-change');
        } catch {}
        resolvedQuill.value = null;
      }

      resolvedQuill.value = new Quill(resolvedQuillRef.value, {
        theme: 'snow',
        modules: {
          toolbar: [['bold', 'italic', 'underline'], [{ color: [] }], ['clean'], ['image']],
        },
      });
    }

    isQuillReady.value = true;
    console.log('✅ Quill 初始化完成', { rootQuill, resolvedQuill });
  }

  function destroyQuillEditors() {
    try {
      if (rootQuill.value) {
        // ⚠️ 彻底清理 DOM 与事件
        rootQuill.value.off('text-change');
        rootQuill.value.root.innerHTML = '';
        rootQuill.value = null;
      }
      if (resolvedQuill.value) {
        resolvedQuill.value.off('text-change');
        resolvedQuill.value.root.innerHTML = '';
        resolvedQuill.value = null;
      }

      // DOM 元素也可以清空（可选）
      if (rootQuillEditor.value) rootQuillEditor.value.innerHTML = '';
      if (resolvedQuillRef.value) resolvedQuillRef.value.innerHTML = '';

      isQuillReady.value = false;
      console.log('🧹 Quill 实例销毁成功');
    } catch (e) {
      console.warn('销毁 Quill 出错', e);
    }
  }

  function getQuillInstance(refName) {
    if (refName === 'rootQuillEditor') return rootQuill.value;
    if (refName === 'resolvedQuillRef') return resolvedQuill.value;
    return null;
  }

  function isCloseDisabled(item) {
    return (
      !(item.status === '已解决' && (item.myCreated || item.pmoOrNot)) &&
      !(item.status === '无需解决' && (item.myCreated || item.pmoOrNot))
    ); // 创建人或PMO关闭
  }
  function isResolvingDisabled(item) {
    return !(item.status === '未开始' && item.solvers);
  }
  function isNoNeedSolveDisabled(item) {
    return !(
      (item.status === '未开始' && item.solvers) ||
      (item.status === '解决中' && item.solvers)
    );
    // !(item.status === '未开始' && item.solvers) || !(item.status === '解决中' && item.solvers)
  }
  function isResolvedDisabled(item) {
    return (
      // !(item.status === '未开始' && item.solvers) && // 解决人解决中
      !(item.status === '解决中' && item.solvers)
    );
  }
  function isReturnVisitDisabled(item) {
    return !(item.status === '已关闭' && (item.myCreated || item.pmoOrNot)); // 创建人或PMO回访
  }
  // 判断按钮是否可用的计算属性
  function isCirculationDisabled(item) {
    if (item.tag === 1) return true; // 如果 tag 是 1，直接禁用按钮
    return !(
      (
        (item.status === '未开始' && item.solvers) || // 未开始且有solvers
        (item.status === '解决中' && item.solvers) || // 解决中且有solvers
        (item.status === '待分发' && item.distributed) ||
        item.tag === 1
      ) // 待分发且distributed为true
    );
  }
  function isEditDisabled(item) {
    if ((item.myCreated || item.solvers) && item.status === '已关闭') {
      return false;
    }
    return ['无需解决', '已解决'].includes(item.status);
  }
  function fatherCancel() {
    state.addOrEditVisible = false;
  }
  const handleSaved = () => {
    state.addOrEditVisible = false;
    // 这里刷新父页面数据
    getData();
  };
  function getData() {
    get(`/solution-ppm-work-order/api/v1/work_order/details/${props.operationForm.id}`).then(
      (data) => {
        if (data.code !== 200) {
          showFailToast(data.message);
          return;
        }
        state.gdDetail = data.data.workOrderDto;
      },
    );
  }
  const editForm = ref({});
  const type = ref('edit');
  // 编辑
  function handleEdit(record) {
    showMoreMenu.value = false;
    // console.log(record);
    editForm.value = cloneDeep(record);
    // state.addOrEditVisible = true;
    uni.setStorageSync('edit_form', editForm.value);
    handleRedirect(`/pages/Page3000001236/Page3000001236?mode=edit`);
  }
  // 开始解决
  const currentResolvingData = ref({});
  function showResolving(record, parentId) {
    showMoreMenu.value = false;
    newSopState.selectedRowKeys = [];
    currentResolvingData.value = record;
    if (parentId) {
      currentResolvingData.value.addParentId = parentId;
    } else {
      currentResolvingData.value.addParentId = record.id;
    }
    newState.workOrderId = record.id;
    showOpen.value = true;
  }
  const resolvingRef = ref(null);
  // 开始解决处理
  async function confirmResolving() {
    newState.changeStatusLoading = true;
    try {
      const selectedSopList = newSopState.sopTableData.filter((item) =>
        newSopState.selectedRowKeys.includes(item.sopStepId),
      );
      newState.resolvingForm.workOrderId = currentResolvingData.value.id;
      const params = {
        attachmentList: newSopState.sopFileList,
        children: selectedSopList,
        parentId: currentResolvingData.value.addParentId,
        endTime: currentResolvingData.value.endTime,
        monitorScene: currentResolvingData.value.monitorScene,
      };

      // 只有当 tag === 1 时，才先执行 createSopChildren
      if (currentResolvingData.value.tag === 1) {
        const createRes = await post(
          '/solution-ppm-work-order/api/v1/work_order/createSopChildren',
          params,
        );
        if (createRes.code !== 200) {
          showFailToast(createRes.message);
          return;
        }
      }

      // 调用 status_change 接口
      const statusChangeRes = await put(
        '/solution-ppm-work-order/api/v1/work_order/status_change',
        newState.resolvingForm,
      );
      console.log(statusChangeRes);

      if (statusChangeRes.code !== 200) {
        showFailToast(statusChangeRes.message);
        return;
      }

      showSuccessToast(statusChangeRes.message);
      cancelResolving();
      resetNewState();
      getData();
      handleDone();
    } catch (error) {
      showFailToast('开始操作失败，请重试');
      console.error('错误详情:', error);
    } finally {
      newState.changeStatusLoading = false;
    }
  }
  // 将 dataURL 转换为 File 对象的辅助函数
  const dataURLtoFile = (dataurl, filename) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  };
  // 上传api
  const uploadFileAPI = async (file) => {
    // 构造 FormData
    const formData = new FormData();
    formData.append('file', file.file || file.originFileObj || file);

    // 打印验证一下
    for (let [key, value] of formData.entries()) {
      console.log('FormData内容:', key, value);
    }

    try {
      const res = await fetch('/file-storage/api/v1/file/upload', {
        method: 'POST',
        body: formData, // ✅ 真正传文件流
        // ⚠️ 不要手动设置 Content-Type，让浏览器自动加 boundary
        // headers: { 'Content-Type': 'multipart/form-data' }, ❌
      });

      if (!res.ok) {
        throw new Error(`上传失败: ${res.status}`);
      }

      const data = await res.json();
      console.log('上传返回:', data);

      // 按你之前接口结构封装返回
      return { data: { fullUrl: data.data.fullUrl } };
    } catch (err) {
      console.error('上传图片出错:', err);
      throw err;
    }
  };
  function cancelResolving() {
    showOpen.value = false;
    currentResolvingData.value = {};
    resolvingRef.value.clearLoading();
  }
  function resetNewState() {
    newSopState.sopTableData = [];
    newSopState.selectedRowKeys = [];
    newSopState.sopFileList = [];
    noNeedData.value = {};
  }
  //   已解决
  // 已解决
  const resolvedData = ref({});
  const resolvedRef = ref(null);
  const resolvedType = ref('resolved');
  function showResolved(record, type) {
    showMoreMenu.value = false;
    resolvedType.value = type;
    if (type === 'noNeed') {
      noNeedData.value = record;
    }

    newSopState.sopTableData = [];
    newSopState.selectedRowKeys = [];
    resolvedData.value = record;
    newState.workOrderId = record.id;
    get(`/solution-ppm-work-order/api/v1/work_order/details/${newState.workOrderId}`).then(
      async (data) => {
        if (data.code !== 200) {
          showFailToast(data.message);
          return;
        }
        showResolvedVisible.value = true;
        rootState.responsibleParty = data.data.workOrderDto.responsibleParty;
        rootState.businessType = data.data.workOrderDto.businessType;
        rootState.rootCauseClassify = data.data.workOrderDto.rootCauseClassify;
        await initQuillEditors();
        nextTick(() => {
          try {
            rootRef.value.setRules(rules);
            if (type === 'noNeed') {
              noNeedRef.value.setRules(rules);
            }

            const solutionDetail = JSON.parse(data.data.workOrderDto.solutionDetail);
            const resolvedInst = getQuillInstance('resolvedQuillRef');
            if (!resolvedInst) throw new Error('resolvedQuill 实例未找到');
            resolvedInst.setContents(solutionDetail);
          } catch (e) {
            console.warn('resolvedQuillRef 富文本赋值失败（不阻断）：', e);
          }
          try {
            const rootCauseAnalysisDetail = JSON.parse(data.data.workOrderDto.rootCauseAnalysis);
            const rootQuillInst = getQuillInstance('rootQuillEditor');
            if (!rootQuillInst) throw new Error('rootQuill 实例未找到');
            console.log(rootQuillInst, 'asdad');

            rootQuillInst.setContents(rootCauseAnalysisDetail);
          } catch (e) {
            console.warn('rootQuillEditor 富文本赋值失败（不阻断）：', e);
          }
          newState.resolvedForm.solution = data.data.workOrderDto.solution;
          newState.resolvedForm.attachmentList = data.data.workOrderDto.attachmentList;
        });
      },
    );
  }
  // 上传文件
  function handlerResolvedUpload(file) {
    newState.changeStatusLoading = true;
    const data = new FormData();
    data.append('file', file);

    post('/file-storage/api/v1/file/upload', data)
      .then(({ data: { fullUrl } }) => {
        if (data) {
          // 新文件对象
          const newFile = {
            uid: file.uid,
            lastModified: file.lastModified,
            name: file.name,
            size: file.size,
            type: file.type,
            status: 'done',
            url: fullUrl,
          };

          // 去重，保留一个副本
          newState.resolvedForm.attachmentList = [
            // 保留已存在文件（去除重复）
            ...newState.resolvedForm.attachmentList.filter(
              (item) => item.uid !== file.uid && item.name !== file.name,
            ),
            // 添加新的文件
            newFile,
          ];
        }
        newState.changeStatusLoading = false;
      })
      .catch((e) => {
        showFailToast('上传失败' + e);
      });

    return false;
  }
  // 移除文件
  function handlerResolvedRemove(file) {
    newState.resolvedForm.attachmentList = newState.resolvedForm.attachmentList.filter(
      (item) => item.uid !== file.uid,
    );
  }
  const resolvedFormRef = ref(null);
  const noNeedRef = ref(null);
  const sonState = reactive({
    noNeedRemark: undefined,
  });
  // 已解决//无需解决处理
  const deltaData = ref(null);
  const rootRef = ref(null);
  async function confirmResolved() {
    newState.changeStatusLoading = true;
    try {
      const resolvedInst = getQuillInstance('resolvedQuillRef');
      if (!resolvedInst) throw new Error('resolvedQuill 实例未找到');

      const deltaContent = resolvedInst.getContents();
      deltaData.value = deltaContent; // 保存一份 delta 数据

      const imageUploadPromises = [];

      deltaContent.ops.forEach((op) => {
        if (op.insert && op.insert.image && op.insert.image.startsWith('data:')) {
          const localSrc = op.insert.image;
          const file = dataURLtoFile(localSrc, 'image.png');

          const uploadPromise = uploadFileAPI(file).then(({ data: { fullUrl } }) => {
            op.insert.image = fullUrl;
          });

          imageUploadPromises.push(uploadPromise);
        }
      });

      await Promise.all(imageUploadPromises);

      // 如果 tag === 1，先调用 createSopChildren 接口
      if (resolvedData.value.tag === 1) {
        const params = {
          attachmentList: newSopState.sopFileList,
          children: newSopState.sopTableData.filter((item) =>
            newSopState.selectedRowKeys.includes(item.sopStepId),
          ),
          parentId: resolvedData.value.addParentId,
          endTime: resolvedData.value.endTime,
          monitorScene: resolvedData.value.monitorScene,
        };

        const createSopResponse = await post(
          '/solution-ppm-work-order/api/v1/work_order/createSopChildren',
          params,
        );

        if (createSopResponse.code !== 200) {
          showFailToast(createSopResponse.message);
          return;
        }
      }

      // 构造最终状态变更数据，注意不要修改 form 本身
      const payload = {
        ...newState.resolvedForm,
        workOrderId: resolvedData.value.id,
        status: '已解决',
        solutionDetail: JSON.stringify(deltaData.value), // 仅提交结构化数据
      };

      const statusChangeResponse = await put(
        '/solution-ppm-work-order/api/v1/work_order/status_change',
        payload,
      );

      if (statusChangeResponse.code !== 200) {
        showFailToast(statusChangeResponse.message);
        return;
      }

      showSuccessToast(statusChangeResponse.message);
      cancelResolved();
      emit('refresh');
      handleDone();
    } catch (error) {
      // 可选：日志
    } finally {
      newState.changeStatusLoading = false;
    }
  }
  async function saveRoot() {
    try {
      // 🚦 1. 如果是 “无需解决”，先校验备注表单
      if (resolvedType.value === 'noNeed') {
        await noNeedRef.value.validate();
      }

      // 🚦 2. 校验根因分析表单
      await rootRef.value.validate();

      // 🚧 3. 构造参数
      const params = {
        responsibleParty: rootState.responsibleParty,
        businessType: rootState.businessType,
        rootCauseClassify: rootState.rootCauseClassify,
        rootCauseAnalysis: '',
        id: resolvedData.value.id,
      };

      // 🧩 4. 处理富文本内容（含图片上传）
      try {
        const rootQuillInst = getQuillInstance('rootQuillEditor');
        if (!rootQuillInst) throw new Error('rootQuill 实例未找到');

        const rootDeltaContent = rootQuillInst.getContents();
        const rootUploadTasks = rootDeltaContent.ops.map(async (op) => {
          if (op.insert?.image?.startsWith('data:')) {
            const file = dataURLtoFile(op.insert.image, 'image.png');
            const {
              data: { fullUrl },
            } = await uploadFileAPI(file);
            op.insert.image = fullUrl;
          }
        });
        await Promise.all(rootUploadTasks);
        params.rootCauseAnalysis = JSON.stringify(rootDeltaContent);
      } catch (e) {
        console.warn('处理富文本出错', e);
      }

      // 🚀 5. 调用接口
      const data = await put(
        '/solution-ppm-work-order/api/v1/work_order/root_cause_modify',
        params,
      );
      console.log(data, 'data');

      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }

      // 🎯 6. 根据类型执行不同后续逻辑
      if (resolvedType.value === 'resolved') {
        confirmResolved();
      } else if (resolvedType.value === 'noNeed') {
        submitNoNeed();
      }
    } catch (err) {
      console.warn('校验或提交失败', err);
      // ❌ 阻止关闭并清除loading

      return;
    } finally {
      // 确保 loading 状态被清掉
    }
  }

  function cancelResolved() {
    showResolvedVisible.value = false;
    resolvedData.value = {};
    sonState.noNeedRemark = undefined;
  }
  const noNeedData = ref({});
  // 无需解决处理
  async function submitNoNeed() {
    console.log('到这里了');

    newState.changeStatusLoading = true;
    try {
      const selectedSopList = newSopState.sopTableData.filter((item) =>
        newSopState.selectedRowKeys.includes(item.sopStepId),
      );
      const params = {
        attachmentList: newSopState.sopFileList,
        children: selectedSopList,
        parentId: noNeedData.value.addParentId,
        endTime: noNeedData.value.endTime,
        monitorScene: noNeedData.value.monitorScene,
      };

      // 只有当 tag === 1 时，才先执行 createSopChildren
      if (noNeedData.value.tag === 1) {
        const createRes = await post(
          '/solution-ppm-work-order/api/v1/work_order/createSopChildren',
          params,
        );
        if (createRes.code !== 200) {
          showFailToast(createRes.message);
          return;
        }
      }

      // 调用 status_change 接口
      const statusChangeRes = await put(
        '/solution-ppm-work-order/api/v1/work_order/status_change',
        {
          remark: sonState.noNeedRemark,
          status: '无需解决',
          workOrderId: noNeedData.value.id,
        },
      );
      if (statusChangeRes.code !== 200) {
        showFailToast(statusChangeRes.message);
        return;
      }

      showSuccessToast(statusChangeRes.message);
      resetNewState();
      getData();
      handleDone();
    } catch (error) {
      if (error?.errorFields) {
        console.log(error);

        // ✅ 这里确保只有校验失败时才会显示
        showFailToast('请检查表单填写是否正确');
      } else {
        showFailToast('操作失败，请重试');
        console.error('错误详情:', error);
      }
    } finally {
      newState.changeStatusLoading = false;
    }
  }
  //     根因分析
  const rootState = reactive({
    // 责任方
    responsibleParty: undefined,
    responsiblePartyList: [],
    // 业务类型
    businessType: undefined,
    businessTypeList: [],
    rootCauseClassifyList: undefined,
    rootCauseClassify: [],
    // 根因分析
    belongList: [],
    tagList: [],
    rootCauseFlag: false,
    tipVisible: false,
  });
  const rules = {
    responsibleParty: [
      { type: 'string', required: true, message: '请选择责任方', trigger: ['blur', 'change'] },
    ],
    businessType: [
      { type: 'string', required: true, message: '请选择业务类型', trigger: ['blur', 'change'] },
    ],

    rootCauseClassify: [
      { type: 'string', required: true, message: '请选择根因分析', trigger: ['blur', 'change'] },
    ],
    noNeedRemark: [
      { type: 'string', required: true, message: '请输入备注', trigger: ['blur', 'change'] },
    ],
    solverList: [
      {
        required: true,
        message: '请选择解决人',
        trigger: ['blur', 'change'],
      },
    ],
    closeRemark: [
      {
        required: true,
        message: '请输入备注',
        trigger: ['blur', 'change'],
      },
    ],
    deleteRemark: [
      {
        required: true,
        message: '请输入备注',
        trigger: ['blur', 'change'],
      },
    ],
  };
  // 显示 Picker
  function showPicker(type) {
    show[type] = true;
    if (type === 'responsibleParty') {
      getResponsiblePartyList();
    } else if (type === 'businessType') {
      getBusinessTypeList();
    } else if (type === 'rootCauseClassify') {
      getRootCauseClassifyList();
    } else if (type === 'solverList') {
      getAllUser();
    }
  }
  function onConfirm(type, val) {
    const selectedVal = val.selectedValues[0];
    rootState[type] = selectedVal;
    show[type] = false;
    if (type === 'solverList') {
      const selected = val.selectedOptions?.[0];
      if (selected) {
        console.log(newState.circulationForm.solverList);
        newState.circulationForm.solverList = selected.label;
      }
    }
    setTimeout(() => {
      switch (type) {
        case 'responsibleParty':
          responsiblePartyChange(selectedVal);
          break;
        case 'businessType':
          businessTypeChange(selectedVal);
          break;
        case 'rootCauseClassify':
          rootCauseClassifyChange(selectedVal);
          break;
        default:
          rootState[type] = selectedVal || val.text;
      }
    }, 200);
  }

  // 获取责任方
  function getResponsiblePartyList() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/GD.ZRF').then((data) => {
      rootState.responsiblePartyList = data.data;
    });
  }

  // 根据责任方获取业务类型
  function getBusinessTypeList() {
    let envId = rootState.responsiblePartyList.find(
      (item) => item.itemName === rootState.responsibleParty,
    )?.itemCode;
    get(` /solution-ppm-basic-data/api/v1/dictionary/search/${envId}`).then((data) => {
      rootState.businessTypeList = data.data;
    });
  }

  // 根据业务类型获取根因分析
  function getRootCauseClassifyList() {
    let envId = rootState.businessTypeList.find(
      (item) => item.itemName === rootState.businessType,
    )?.itemCode;
    get(` /solution-ppm-basic-data/api/v1/dictionary/search/${envId}`).then((data) => {
      rootState.rootCauseClassifyList = data.data.map((item) => {
        return {
          ...item,
        };
      });
    });
  }
  // 保存切换前值
  const preState = reactive({
    responsibleParty: undefined,
    businessType: undefined,
    rootCauseClassify: undefined,
  });

  // 弹窗控制
  const tipState = reactive({
    visible: false,
    pendingField: '', // 'responsibleParty' | 'businessType' | 'rootCauseClassify'
    nextValue: undefined,
  });

  // 判断富文本是否有内容
  function hasEditorContent() {
    const rootQuillInst = getQuillInstance('rootQuillEditor');
    if (!rootQuillInst) throw new Error('rootQuill 实例未找到');

    const content = rootQuillInst?.getText() || '';
    console.log(content);
    return content.trim().length > 0;
  }

  // === 责任方 change ===
  function responsiblePartyChange(nextVal) {
    if (hasEditorContent()) {
      tipState.visible = true;
      tipState.pendingField = 'responsibleParty';
      tipState.nextValue = nextVal;
      // 还原选择框临时值
      rootState.responsibleParty = preState.responsibleParty;
      return;
    }
    console.log('走到外面触发applyResponsiblePartyChange');

    applyResponsiblePartyChange(nextVal);
  }
  function applyResponsiblePartyChange(val) {
    console.log('触发applyResponsiblePartyChange');
    clearEditor();
    rootState.responsibleParty = val;
    preState.responsibleParty = val;
    rootState.businessType = undefined;
    preState.businessType = undefined;
    rootState.rootCauseClassify = undefined;
    preState.rootCauseClassify = undefined;

    getBusinessTypeList();
  }

  // === 业务类型 change ===
  function businessTypeChange(nextVal) {
    if (hasEditorContent()) {
      tipState.visible = true;
      tipState.pendingField = 'businessType';
      tipState.nextValue = nextVal;
      rootState.businessType = preState.businessType;
      return;
    }
    applyBusinessTypeChange(nextVal);
  }
  function applyBusinessTypeChange(val) {
    rootState.businessType = val;
    preState.businessType = val;
    rootState.rootCauseClassify = undefined;
    preState.rootCauseClassify = undefined;
    clearEditor();
    getRootCauseClassifyList();
  }

  // === 根因分析 change ===
  function rootCauseClassifyChange(nextVal) {
    if (hasEditorContent()) {
      tipState.visible = true;
      tipState.pendingField = 'rootCauseClassify';
      tipState.nextValue = nextVal;
      rootState.rootCauseClassify = preState.rootCauseClassify;
      return;
    }
    applyRootCauseClassifyChange(nextVal);
  }
  function applyRootCauseClassifyChange(val) {
    rootState.rootCauseClassify = val;
    preState.rootCauseClassify = val;
    const selected = rootState.rootCauseClassifyList.find((item) => item.itemName === val);
    const description = selected?.description || '';
    setEditorText(description);
  }

  // === 弹窗确认 ===
  function confirmRoot() {
    const field = tipState.pendingField;
    const val = tipState.nextValue;

    if (field === 'responsibleParty') {
      applyResponsiblePartyChange(val);
    } else if (field === 'businessType') {
      applyBusinessTypeChange(val);
    } else if (field === 'rootCauseClassify') {
      applyRootCauseClassifyChange(val);
    }

    tipState.visible = false;
  }

  // 弹窗取消
  function cancelRoot() {
    tipState.visible = false;
  }

  // 清空富文本
  function clearEditor() {
    const rootQuillInst = getQuillInstance('rootQuillEditor');
    if (!rootQuillInst) throw new Error('rootQuill 实例未找到');
    console.log(rootQuillInst);
    rootQuillInst?.setText('');
  }

  // 赋值富文本
  function setEditorText(text) {
    nextTick(() => {
      const rootQuillInst = getQuillInstance('rootQuillEditor');
      if (!rootQuillInst) throw new Error('rootQuill 实例未找到');
      console.log(rootQuillInst);
      rootQuillInst?.setText(text);
    });
  }
  import { watchEffect } from 'vue';
  // 初始赋值 preState
  watchEffect(() => {
    preState.responsibleParty = rootState.responsibleParty;
    preState.businessType = rootState.businessType;
    preState.rootCauseClassify = rootState.rootCauseClassify;
  });
  //   流转
  const circulatuonModalRef = ref(null);
  const circulationFormRef = ref(null);
  function showCirculation(record) {
    newState.circulationVisible = true;
    nextTick(() => {
      circulationFormRef?.value?.setRules(rules);
    });
    newState.workOrderId = record.id;
  }
  // 流转处理
  function confirmCirculation() {
    circulationFormRef.value
      .validate()
      .then(() => {
        newState.changeStatusLoading = true;
        newState.circulationForm.workOrderId = newState.workOrderId;
        newState.circulationForm.status = '未开始';
        newState.circulationForm.solverList = [newState.circulationForm.solverList];
        put('/solution-ppm-work-order/api/v1/work_order/status_change', newState.circulationForm)
          .then((data) => {
            if (data.code !== 200) {
              showFailToast(data.message);
              return;
            }
            showSuccessToast(data.message);
            cancelCirculation();
            emit('refresh');
            handleDone();
          })
          .finally(() => {
            newState.changeStatusLoading = false;
            circulatuonModalRef.value.clearLoading();
            cancelCirculation();
          });
      })
      .catch(() => {
        circulatuonModalRef.value.clearLoading();
      });
  }

  // 基础信息获取
  function getAllUser() {
    get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.allUser = data.data.userDtoList.map((item) => {
        return {
          label: item.name,
          value: item.name,
        };
      });
    });
  }
  function cancelCirculation() {
    newState.circulationVisible = false;
    newState.circulationForm = {
      solverList: [],
      status: '流转',
    };
  }
  function resetCurrentData() {
    currentData.value = {};
  }
  const currentData = ref({});
  // 删除
  function toDelete(record) {
    resetCurrentData();
    currentData.value = record;
    state.deleteVisible = true;
    nextTick(() => {
      deleteRef.value.setRules(rules);
    });
  }
  const deleteRef = ref(null);
  const deleteModalRef = ref(null);
  // 删除处理
  function handleDelete() {
    deleteRef.value
      .validate()
      .then(() => {
        del(`/solution-ppm-work-order/api/v1/work_order/${currentData.value.id}`)
          .then((data) => {
            if (data.code !== 200) {
              showFailToast(data.message);
              return;
            }
            showSuccessToast(data.message);
            state.deleteVisible = false;
            handleDone();
            deleteModalRef.value.clearLoading();
          })
          .finally(() => {
            deleteModalRef.value.clearLoading();
          });
      })
      .catch(() => {
        deleteModalRef.value.clearLoading();
      });
  }
  // 工单开始关闭
  const currentCloseData = ref({});
  function handlerClose(item, parentId) {
    newSopState.selectedRowKeys = [];
    currentCloseData.value = item;
    if (parentId) {
      currentCloseData.value.addParentId = parentId;
    } else {
      currentCloseData.value.addParentId = item.id;
    }
    if (item.tag === 1) {
      get(`/solution-ppm-work-order/api/v1/work_order/${item.id}/sop/steps`).then((data) => {
        if (data.code !== 200) {
          showFailToast(data.message);
          return;
        }
        // newSopState.sopTableData = groupSopData(data.data.filter(item => item.canCreated))
        newSopState.sopTableData = groupSopData(data.data);
      });
    } else {
      newSopState.sopTableData = [];
    }

    newSopState.sopCloseVisible = true;
    nextTick(() => {
      closeRef.value.setRules(rules);
    });
  }
  const closeModalRef = ref(null);
  const closeRef = ref(null);
  // 工单关闭处理
  // 工单确定关闭
  async function confirmSopClose() {
    newSopState.closeLoading = true;
    try {
      // ✅ 直接 await 表单校验，不需要 catch
      await closeRef.value.validate();

      const selectedSopList = newSopState.sopTableData.filter((item) =>
        newSopState.selectedRowKeys.includes(item.sopStepId),
      );
      const params = {
        attachmentList: newSopState.sopFileList,
        children: selectedSopList,
        parentId: currentCloseData.value.addParentId,
        endTime: currentCloseData.value.endTime,
        monitorScene: currentCloseData.value.monitorScene,
      };

      // 只有当 tag === 1 时，才先执行 createSopChildren
      if (currentCloseData.value.tag === 1) {
        const createRes = await post(
          '/solution-ppm-work-order/api/v1/work_order/createSopChildren',
          params,
        );
        if (createRes.code !== 200) {
          showFailToast(createRes.message);
          return;
        }
      }

      // 调用 status_change 接口
      const statusChangeRes = await put(
        '/solution-ppm-work-order/api/v1/work_order/status_change',
        {
          remark: newSopState.closeRemark,
          status: '已关闭',
          workOrderId: currentCloseData.value.id,
        },
      );
      if (statusChangeRes.code !== 200) {
        showFailToast(statusChangeRes.message);
        return;
      }

      showSuccessToast(statusChangeRes.message);
      cancelClose();
      resetNewState();
      getData();
      handleDone();
    } catch (error) {
      if (error?.errorFields) {
        // ✅ 这里确保只有校验失败时才会显示
        showFailToast('请检查表单填写是否正确');
      } else {
        showFailToast('操作失败，请重试');
        console.error('错误详情:', error);
      }
      closeModalRef.value.clearLoading();
    } finally {
      newSopState.closeLoading = false;
      closeModalRef.value.clearLoading();
    }
  }
  function cancelClose() {
    newSopState.sopCloseVisible = false;
    newSopState.closeRemark = undefined;
    currentCloseData.value = {};
  }
  // 重新打开
  function handlerReOpen(item) {
    const params = {
      workOrderId: item.id,
      status: '未开始',
    };
    if (item.actualStartTime) {
      params.status = '解决中';
    } else {
      params.status = '未开始';
    }
    put('/solution-ppm-work-order/api/v1/work_order/status_change', params).then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      showSuccessToast(data.message);
      getData();
      handleDone();
    });
  }
  // 定义事件：关闭弹窗 / 保存成功f
  const emit = defineEmits(['refresh']);
  function handleDone() {
    console.log('[OperationButton] emit refresh');
    // 子组件某操作完成
    emit('refresh');
  }
</script>
<style lang="less" scoped>
  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: hidden;
    background-image: none !important;
  }
  .father-last {
    display: flex;
    gap: 16px;
  }
  .quill-editor {
    min-height: 200rpx;
    background: #fff;
  }
  :deep(.ql-toolbar .ql-formats .ql-bold) {
    width: 56rpx;
    height: 48rpx;
    border: none !important;
  }
  :deep(.ql-toolbar .ql-formats .ql-italic) {
    border: none !important;
  }
  :deep(.ql-toolbar .ql-formats .ql-underline) {
    border: none !important;
  }
  :deep(.ql-toolbar .ql-formats .ql-clean) {
    border: none !important;
  }
  :deep(.ql-toolbar .ql-formats .ql-picker-label) {
    padding: 0;
    text-align: center;
    line-height: 30rpx;
  }
  :deep(.ql-toolbar .ql-image) {
    padding: 0;
    border: none !important;
    background: transparent;
  }
  :deep(.ql-formats svg) {
    width: 20rpx;
    height: 20rpx;
  }
  :deep(.ql-formats) {
    margin: 0 !important;
  }
  //   :deep(.van-cell__title) {
  //     width: 100rpx;
  //   }
  .editor-wrap {
    font-size: 14px;
    color: #323233;
    .label {
      margin-bottom: 10px;
    }
    margin-bottom: 32rpx;
  }
  .text-gray-600 {
    padding: 16rpx;
  }

  .no-need-tip {
    padding: 20rpx 32rpx;
  }

  .field-bordered:deep(.van-field__control) {
    border: 1px solid #d9d9d9;
    padding: 0 20rpx;
    border-radius: 8rpx;
  }
  .tip-font {
    font-size: 28rpx;
  }
  .popup-more-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
  }
  .show-more {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.65);
    text-align: center;
    font-weight: 400;
    height: 80rpx;
    line-height: 80rpx;
  }
  .other-btn {
    flex: 1;
    display: flex;
    justify-content: end;
    gap: 16rpx;
  }
  .bgc:deep(.u-drawer-content) {
    background-image: url('http://10.40.0.33:9001/file-storage/540482118078511104-source.png');
    background-size: cover !important;
    background-repeat: 'no-repeat' !important;
    background-position: 'center' !important;
    border-radius: 32rpx !important;
  }
  .popup-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;
  }
  .fixed-header {
    flex-shrink: 0;
    text-align: center;
  }
  /* 顶部标题固定 */

  .scrollable-content {
    flex: 1;
    padding: 30rpx;
    padding-bottom: 240rpx; /* 为底部按钮留出足够空间 */
  }

  .fixed-footer {
    position: fixed;
    bottom: 100rpx;
    left: 0;
    right: 0;
    height: 120rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    gap: 32rpx;
  }
  .can-btn {
    width: 30%;
  }
  .ok-btn {
    flex: 1;
  }
  .pop-title {
    font-size: 36rpx;
    color: #333333;
    font-weight: 500;
    padding: 24rpx 0;
    width: 100%;
    flex-shrink: 0;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    padding: 24rpx;
    position: sticky;
    top: 0;
    z-index: 10;
  }

  :deep(.ql-toolbar) {
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    border: none;
    background-color: #f3f6ff;
  }
  :deep(.quill-editor) {
    border-bottom-left-radius: 20rpx;
    border-bottom-right-radius: 20rpx;
    background-color: #f3f6ff;
    border: none;
  }
  :deep(.ql-toolbar .ql-formats .ql-bold) {
    border: none !important;
    background: transparent;
  }

  :deep(.ql-toolbar .ql-formats .ql-italic) {
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-formats .ql-active) {
    background: #dbeafe !important;
  }
  :deep(.ql-toolbar .ql-formats .ql-underline) {
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-formats .ql-clean) {
    border: none !important;
    background: transparent;
  }
  :deep(.ql-toolbar .ql-formats .ql-picker-label) {
    padding: 0;
    text-align: center;
  }
  .popup-container :deep(.u-form) {
    height: auto !important;
  }
</style>
